//
//  TimeTrackerViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 1/13/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "ActivitiesViewController.h"
#import "ActivityCell.h"
#import "ActivityDetailViewController.h"

@interface ActivitiesViewController ()

@end

@implementation ActivitiesViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self loadActivities];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _activityIDs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"activityTableCell";
    
    ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    int row = [indexPath row];
    
    cell.activityNameLabel.text = _activityNames[row];
    cell.categoryNameLabel.text = _categoryNames[row];
    
    // if currently active, set switch to "on", else "off"
    [cell.activityTrackerSwitch setOn:NO animated:NO];
    for(int i=0;i<_activeActivityIds.count;i++)
    {
        if([_activeActivityIds[i] intValue] == [_activityIDs[row] intValue])
        {
            [cell.activityTrackerSwitch setOn:YES animated:NO];
        }
    }
    cell.activityTrackerSwitch.restorationIdentifier = _activityIDs[row];
    [cell.activityTrackerSwitch addTarget:self action:@selector(switchPressed:) forControlEvents:UIControlEventValueChanged];
    
    return cell;
}

- (void)switchPressed:(id)sender
{
    BOOL on = [sender isOn];

    // update database
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            NSDateFormatter *format = [[NSDateFormatter alloc] init];
            [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *now = [[NSDate alloc] init];
            
            NSString *query = @"";
            if(on)
            {
                // switch changed from "off" to "on", create a new tasklog entry for the activity and set the start_time to now and end_time to null
                
                NSString *startTime = [format stringFromDate:now];
                
                query = [NSString stringWithFormat:@"INSERT INTO tasklog (activity_id,start_time,end_time,notes) VALUES(%s,'%@',null,'')",[[sender restorationIdentifier] UTF8String],startTime];
                
                
            } else {
                
                // switch changed from "on" to "off", set the end_time to now for this activity_id where the end_time is currently null
                NSString *endTime = [format stringFromDate:now];
                query = [NSString stringWithFormat:@"update tasklog set end_time = '%@' where activity_id = '%s' and end_time is null",endTime,[[sender restorationIdentifier] UTF8String]];
            }
            
            const char *query_const = [query UTF8String];
            //NSLog(@"query: %s",query_const);
            
            sqlite3_stmt *res;
            if(sqlite3_prepare(_database, query_const, -1, &res, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",query_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                if(SQLITE_DONE != sqlite3_step(res))
                    NSAssert1(0, @"Database query errror. '%s'", sqlite3_errmsg(_database));
                sqlite3_finalize(res);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivitiesViewController");
        }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}


- (void)loadActivities
{
    // load data from database
    _activityIDs = [[NSMutableArray alloc] init];
    _activityNames = [[NSMutableArray alloc] init];
    _categoryNames = [[NSMutableArray alloc] init];
    _categoryIDs = [[NSMutableArray alloc] init];
    _activeActivityIds = [[NSMutableArray alloc] init];
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            // load all active activities
            NSString *select_activities = [NSString stringWithFormat:@"SELECT activities.id, activity_name, category_id, categories.name from activities,categories where categories.id = activities.category_id and activities.active = 1 order by activity_name"];
            const char *select_activities_const = [select_activities UTF8String];
            
            sqlite3_stmt *res_activities;
            if(sqlite3_prepare(_database, select_activities_const, -1, &res_activities, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_activities_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                while (sqlite3_step(res_activities)==SQLITE_ROW) {
                    
                    //NSLog(@"Found an activity");
                    
                    
                    [_activityIDs addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_activities,0)]];
                    [_activityNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_activities,1)]];
                    [_categoryIDs addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_activities,2)]];
                    [_categoryNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_activities,3)]];
                    
                }
                sqlite3_finalize(res_activities);
            }
            
            
            // load all activities that are currently tracking (start_time is not null and end_time is null)
            NSString *select_active_activities = [NSString stringWithFormat:@"SELECT activities.id, activity_name from activities,tasklog where tasklog.activity_id = activities.id and tasklog.start_time is not null and tasklog.end_time is null"];
            const char *select_active_activities_const = [select_active_activities UTF8String];
            
            sqlite3_stmt *res_active_activities;
            if(sqlite3_prepare(_database, select_active_activities_const, -1, &res_active_activities, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_active_activities_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                while (sqlite3_step(res_active_activities)==SQLITE_ROW) {
                    
                    //NSLog(@"Found an active activity: %@",[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_active_activities,1)]);
                    
                    [_activeActivityIds addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_active_activities,0)]];
                }
                sqlite3_finalize(res_active_activities);
            }

            
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }

}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"ShowActivityDetails"])
    {
        ActivityDetailViewController *detailViewController = [segue destinationViewController];
        
        NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
        
        int row = [myIndexPath row];
        
        detailViewController.activityDetailModel = @[_activityIDs[row],_activityNames[row],_categoryIDs[row],_categoryNames[row]];
    }
}



// functions for deleting
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"row selected to be deleted: %d",[indexPath row]);
    
     @try {
     
         // connect to db
     
         NSString *docsDir;
         NSArray *dirPaths;
     
         // Get the documents directory
         dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     
         docsDir = dirPaths[0];
     
         // Build the path to the database file
         _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
     
         NSFileManager *filemgr = [NSFileManager defaultManager];
     
         // check to see if database already exists...
         if ([filemgr fileExistsAtPath: _databasePath ] == YES)
         {
            // open database
             if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
             {
                 NSLog(@"An error has occured when trying to open the database");
             }  
     
             char *errMsg;
             
             // TODO: check to make sure category is not assigned to activities
             // possible solutions: display alert to user OR assign activities to special "Uncategorized" category that cannot be deleted
     
         
             // delete activity
             NSString *delete_sql = [NSString stringWithFormat:@"update activities set active = 0 where id = '%@'",_activityIDs[[indexPath row]]];
             NSLog(@"delete query: %@",delete_sql);
             const char *delete_sql_const = [delete_sql UTF8String];
             if (sqlite3_exec(_database, delete_sql_const, NULL, NULL, &errMsg) != SQLITE_OK)
                 NSLog(@"Failed: %s",errMsg);
         }
         else
         {
             NSLog(@"Error: database could not be found in ActivitiesViewController");
         }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"editing is done... reload the table");
    [self loadActivities];
    [self.tableView reloadData];
}


- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
	// Do not indent rows when in editing mode.
	return NO;
}





- (void)viewDidUnload {
    [self setTrackerSwitchPressed:nil];
    [super viewDidUnload];
}
@end
